package com.ewhale.feitengguest.ui.shop

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import android.widget.RadioGroup
import androidx.fragment.app.Fragment
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.presenter.user.MainPresenter
import com.ewhale.feitengguest.ui.shop.deal.DealFragment
import com.ewhale.feitengguest.ui.shop.mine.SMineFragment
import com.ewhale.feitengguest.ui.shop.msg.SMessageFragment
import com.ewhale.feitengguest.ui.shop.release.ReleaseTaskActivity
import com.ewhale.feitengguest.ui.shop.task.STaskFragment
import com.ewhale.feitengguest.ui.user.MainActivity
import com.ewhale.feitengguest.utils.UserInfoUtils
import com.simga.library.activity.MBaseActivity
import com.simga.library.utils.HawkKey
import kotlinx.android.synthetic.main.activity_shop_main.*

/**
 * 作者：SimGa
 * 日期：2019/12/31
 * 时间：17:54
 * 包名：com.ewhale.feitengguest.ui
 */
open class ShopMainActivity : MBaseActivity<MainPresenter>() {

    override fun getViewId(): Int {
        return R.layout.activity_shop_main
    }
    override fun isUseBaseTitleBar(): Boolean {
        return false
    }
    override fun init(savedInstanceState: Bundle?) {
        replaceFragment(DealFragment::class.java.name)
        registerReceiver()
    }
    override fun initListener() {
        super.initListener()
        radioGroup.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { group, checkedId ->
            val checkView = findViewById<View>(checkedId)
            if (!checkView.isPressed) {
                return@OnCheckedChangeListener
            }
            when (checkedId) {
                R.id.rb_deal -> replaceFragment(DealFragment::class.java.name)
                R.id.rb_task -> replaceFragment(STaskFragment::class.java.name)
                R.id.rb_message -> replaceFragment(SMessageFragment::class.java.name)
                R.id.rb_mine -> replaceFragment(SMineFragment::class.java.name)
            }
        })
        iv_release.setOnClickListener {
            ReleaseTaskActivity.open(mContext)
        }
    }

    private var lastTimePressed: Long = 0

    override fun onBackPressed() {
        if (System.currentTimeMillis() - lastTimePressed < 1000) {
            finishSimple()
        } else {
            lastTimePressed = System.currentTimeMillis()
            showToast("再按一次退出程序")
        }
    }
    private fun replaceFragment(tag: String) {
        var tempFragment = supportFragmentManager.findFragmentByTag(tag)
        val transaction = supportFragmentManager.beginTransaction()
        if (tempFragment == null) {
            try {
                tempFragment = Class.forName(tag).newInstance() as Fragment
                transaction.add(R.id.fragmentContainer, tempFragment, tag)
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
        val fragments = supportFragmentManager.fragments
        if (fragments != null) {
            for (i in fragments.indices) {
                val fragment = fragments[i]
                if (fragment.tag == tag) {
                    transaction.show(fragment)
                } else
                    transaction.hide(fragment)
            }
        }
        transaction.commitAllowingStateLoss()
    }


    private fun registerReceiver() {
        val filter = IntentFilter()
        filter.addAction(HawkKey.SHOP_LOGIN_OUT)
        registerReceiver(myReceiver, filter)
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(myReceiver)
    }

    private val myReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == HawkKey.SHOP_LOGIN_OUT|| intent.action == HawkKey.USER_LOGIN_OUT) {
                UserInfoUtils.deleteUserInfo(2);
                MainActivity.open(mContext)
//                //未登录或者登录失效，跳转至首页
//                val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
//                val activityName = am.getRunningTasks(1)[0].topActivity.className
//                try {
//                    val classObject = Class.forName(activityName)
//                    if (classObject.simpleName == "MainActivity") {
//                        radioGroup.check(R.id.rb_task)
//                        replaceFragment(TaskFragment::class.java.name)
//                    }
//                } catch (e: ClassNotFoundException) {
//                    e.printStackTrace()
//                }
            }
        }
    }

    companion object {
        @JvmStatic
        fun open(mContext: MBaseActivity<*>) {
            mContext.startActivity(null, ShopMainActivity::class.java)
        }
    }
}
